package com.feicheng.common.mqtt;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MqttInboundChannel {

    @Value("${spring.mqtt.username}")
    protected String username;

    @Value("${spring.mqtt.password}")
    protected String password;

    @Value("${spring.mqtt.url}")
    protected String url;

    private MyMqttAsyncClient client;

    @Autowired
    MqttClientCallBack mqttClientCallBack;

    @Value("${mqtt.enable}")
    Boolean mqttEnabled;

    @PostConstruct
    public void init() {
        if (mqttEnabled) {
            connect();
        }
    }

    public Boolean getMqttClientStu() {

        if (null == this.client) {
            return false;
        }

        return this.client.isConnected();
    }

    public void addTopic(String topic) {
        try {
            client.subscribe(topic, 1);
        } catch (Exception e) {
            log.error("订阅频道失败", e);
        }
    }

    private void connect() {
        MqttConnectOptions option = new MqttConnectOptions();
        option.setCleanSession(true);
        option.setUserName(username);
        option.setPassword(password.toCharArray());
        option.setConnectionTimeout(60);
        option.setKeepAliveInterval(20);
        option.setAutomaticReconnect(true);

        try {
            client = new MyMqttAsyncClient(url, "server-inbound", new MemoryPersistence());
            client.setCallback(mqttClientCallBack);
            mqttClientCallBack.setClient(client);

            client.connect(option, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken iMqttToken) {
                    log.info("接收通道MQTT连接成功");
                    try {
                        client.subscribe("mqtt/face/basic", 1);
                        client.subscribe("mqtt/face/heartbeat", 1);
                        log.info("订阅频道成功");
                    } catch (MqttException e) {
                        log.error("订阅频道失败", e);
                    }
                }

                @Override
                public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
                    log.error("接收通道MQTT连接失败", throwable);
                    connect();
                }
            });
        } catch (MqttException e) {
            log.error("接收通道连接MQTT失败", e);
            while (!getMqttClientStu()) {
                try {
                    Thread.sleep(100000L);
                } catch (Exception e1) {

                }
                connect();
            }
        }

    }

    public void disConnect() {
        try {
            client.disconnect();
        } catch (MqttException e) {
            log.error("", e);
        }
    }
}
